import tkinter as tk
from tkinter.messagebox import showwarning

from commons.public_gobals import PublicGlobals
from mes.GetcompleteInfo import GetcompleteInfo


class SnPopup(tk.Toplevel):
    def __init__(self, strVar:tk.StringVar, boolVar:tk.BooleanVar, sn_length:tk.IntVar, **kwargs):
        super().__init__(**kwargs)
        self.strVar = strVar        # 传递变量
        self.boolVar = boolVar
        self.sn_length = sn_length

        self.title("输入SN")
        self.geometry("300x100+200+200")
        self.focus()
        if PublicGlobals.MES_Enable:
            self.config(bg='yellow')
        else:
            self.config(bg='#f0f0f0')

        # self.bind("<Key>", keyBoard_event)
        # self.protocol("WM_DELETE_WINDOW", on_closing)
        # 添加内容
        self.frame = tk.Frame(self)
        self.label = tk.Label(self.frame, text="SN:",height=2)
        self.sn_entry = tk.Entry(self.frame, textvariable=self.strVar,font=('Arial',16))
        self.label.pack(side='left')
        self.sn_entry.pack(side='left')
        self.frame.pack(pady=10)
        close_btn = tk.Button(self, text="关闭", command=lambda: self.close_popup())
        close_btn.pack()
        self.sn_entry.bind('<Return>', self.sn_return)
        self.sn_entry.focus_set()
        # if self.sn_length.get() == 0:
        #     self.sn_return(None)


    def sn_return(self, e):
        # 当长度相等时，关闭窗口进行测试,记录流水号，进行测试
        # 如果要过mes，需要新增逻辑，
        #   访问站点检测接口，成功访问则继续。
        #   失败访问，则弹出提示框，停留在这里。
        if len(self.strVar.get()) == self.sn_length.get():
            if PublicGlobals.MES_Enable:
                try:
                    flag = GetcompleteInfo(url=PublicGlobals.url, barCode=self.strVar.get(),
                                    stationId=PublicGlobals.stationID)
                except Exception as e:
                    flag = False
                    showwarning(message=f'访问接口失败,{e}')
                    self.sn_entry.focus_set()
                    self.strVar.set('')
                if flag:
                    self.boolVar.set(value=True)
                    self.destroy()  # 关闭窗口
            else:
                self.boolVar.set(value=True)
                self.destroy()                  # 关闭窗口
        else:
            pass

    def close_popup(self):
        self.boolVar.set(value=False)
        self.destroy()